package com.example.haohao.myview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class FlowLayout extends ViewGroup {
    int realWidth;
    int realHeight;

    ArrayList<String> lists=new ArrayList<>();
    private Paint paint;

    public FlowLayout(Context context) {
        this(context,null);
    }

    public FlowLayout(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public FlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);

    }
    /**
     * 默认返回的LayoutParams
     */
    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(), attrs);
    }


//    计算子控件宽，高
//    计算自身宽高
    int childWidthTotal;
    int childHeightTotal;

    /**
     * 记录每一行的宽度，width不断取最大宽度
     */
    int lineWidth = 0;
    /**
     * 每一行的高度，累加至height
     */
    int lineHeight = 0;

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

//        int paddingTop=getPaddingTop();
//        int paddingBottom=getPaddingBottom();
//        int paddingLeft=getPaddingLeft();
//        int paddingRight=getPaddingRight();
//
//        for (int i = 0; i < getChildCount(); i++) {
//            System.out.println("子view测量出的宽度为“：" + px2dip(getContext(), getChildAt(i).getMeasuredWidth()));
//            View child = getChildAt(i);
//            LayoutParams childLayout = child.getLayoutParams();
//            int childWidth = getChildMeasureSpec(widthMeasureSpec, paddingLeft + paddingRight, childLayout.width);
//            int childHeight = getChildMeasureSpec(heightMeasureSpec, paddingTop + paddingBottom, childLayout.height);
//           measureChild(child,widthMeasureSpec,heightMeasureSpec);
//            //获得子控件的高度和宽度
//
//            if (childWidth>MeasureSpec.getSize(widthMeasureSpec)) {
//
//
//                childWidth = Math.max(lineWidth, childWidth);// 取最大的
//                lineWidth = childWidth; // 重新开启新行，开始记录
//                // 叠加当前高度，
//                childHeightTotal += childHeight;
//                // 开启记录下一行的高度
//                lineHeight = childHeight;
//
//            }else {
//                lineWidth+=childWidth;
//                lineHeight = Math.max(lineHeight, childHeight);
//            }
//        }
//
//        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
//        int heighMode = MeasureSpec.getMode(heightMeasureSpec);
//        int selfWidth=MeasureSpec.getSize(widthMeasureSpec);
//        int selfHeight=MeasureSpec.getSize(heightMeasureSpec);
//
//
//        realHeight= heighMode==MeasureSpec.EXACTLY?Math.max(selfHeight,childHeightTotal):childHeightTotal;
//        realWidth= widthMode==MeasureSpec.EXACTLY?Math.max(selfWidth,childWidthTotal):selfWidth;
////
////
////
////
//////        3，设置宽高给画布
//        setMeasuredDimension(realWidth, realHeight);


//测量所有子控件
//        measureChildren(widthMeasureSpec, heightMeasureSpec);

        // 获得它的父容器为它设置的测量模式和大小
        int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
        int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
        int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
        int modeHeight = MeasureSpec.getMode(heightMeasureSpec);


        // 如果是warp_content情况下，记录宽和高
        int width = 0;
        int height = 0;
        /**
         * 记录每一行的宽度，width不断取最大宽度
         */
        int lineWidth = 0;
        /**
         * 每一行的高度，累加至height
         */
        int lineHeight = 0;

        int cCount = getChildCount();

        // 遍历每个子元素
        for (int i = 0; i < cCount; i++) {
            View child = getChildAt(i);
            // 测量每一个child的宽和高
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
            // 得到child的lp
            MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
            // 当前子空间实际占据的宽度
            int childWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
            // 当前子空间实际占据的高度
            int childHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;
            /**
             * 如果加入当前child，则超出最大宽度，则的到目前最大宽度给width，类加height 然后开启新行
             */
            if (lineWidth + childWidth > sizeWidth) {
                width = Math.max(lineWidth, childWidth);// 取最大的
                lineWidth = childWidth; // 重新开启新行，开始记录
                // 叠加当前高度，
                height += lineHeight;
                // 开启记录下一行的高度
                lineHeight = childHeight;
            } else{// 否则累加值lineWidth,lineHeight取最大高度
                lineWidth += childWidth;
                lineHeight = Math.max(lineHeight, childHeight);
            }
            // 如果是最后一个，则将当前记录的最大宽度和当前lineWidth做比较
            if (i == cCount - 1) {
                width = Math.max(width, lineWidth);
                height += lineHeight;
            }

        }
        setMeasuredDimension(
                modeWidth == MeasureSpec.EXACTLY ? sizeWidth : width,
                modeHeight == MeasureSpec.EXACTLY? sizeHeight : height);

    }




    /**
     * 存储所有的View，按行记录
     */
    private List<List<View>> mAllViews = new ArrayList<List<View>>();
    /**
     * 记录每一行的最大高度
     */
    private List<Integer> mLineHeight = new ArrayList<Integer>();


    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {

/*     最粗略的摆放，没有计算margin，显示异常
   //获得子控件的数量
        int childCount = getChildCount();
        //当前子控件的左边坐标
        int cl = 0;
        //当前子控件的上边坐标
        int ct = 0;
        //ViewGroup整体宽度
        int width = r - l;
        //行高
        int lineHeight = 0;
        //遍历所有子控件
        for(int i = 0; i < childCount; i++){
            //获取当前控件
            View childAt = getChildAt(i);
            //获取宽度
            int cw = childAt.getMeasuredWidth();
            //获取高度
            int ch = childAt.getMeasuredHeight();
            //当前控件右边
            int cr = cl + cw;
            //当前控件下边
            int cb = ct + ch;
            //判断是否换行
            if(cr > width){
                //如果换行重新计算上下左右地值
                cl = 0;
                cr = cl + cw;
                ct += lineHeight;
                cb = ct + ch;
                //换行后，第一个控件作为最大行高
                lineHeight = ch;
            }else{
                //如果不换行，需要计算最大高度
                lineHeight = Math.max(lineHeight,ch);
            }
            childAt.layout(cl,ct,cr,cb);
            //横向向后移动一个，前面控件的右边作为后面控件的左边
            cl = cr;
        }*/


        mAllViews.clear();
        mLineHeight.clear();

        int width = getWidth();

        int lineWidth = 0;
        int lineHeight = 0;
        // 存储每一行所有的childView
        List<View> lineViews = new ArrayList<View>();
        int cCount = getChildCount();
        // 遍历所有的孩子
        for (int i = 0; i < cCount; i++)
        {
            View child = getChildAt(i);
            MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
            int childWidth = child.getMeasuredWidth();
            int childHeight = child.getMeasuredHeight();

            // 如果已经需要换行
            if (childWidth + lp.leftMargin + lp.rightMargin + lineWidth > width)
            {
                // 记录这一行所有的View以及最大高度
                mLineHeight.add(lineHeight);
                // 将当前行的childView保存，然后开启新的ArrayList保存下一行的childView
                mAllViews.add(lineViews);
                lineWidth = 0;// 重置行宽
                lineViews = new ArrayList<View>();
            }
            /**
             * 如果不需要换行，则累加
             */
            lineWidth += childWidth + lp.leftMargin + lp.rightMargin;
            lineHeight = Math.max(lineHeight, childHeight + lp.topMargin + lp.bottomMargin);
            lineViews.add(child);
        }
        // 记录最后一行
        mLineHeight.add(lineHeight);
        mAllViews.add(lineViews);

        int left = 0;
        int top = 0;
        // 得到总行数
        int lineNums = mAllViews.size();
        for (int i = 0; i < lineNums; i++) {
            // 每一行的所有的views
            lineViews = mAllViews.get(i);
            // 当前行的最大高度
            lineHeight = mLineHeight.get(i);

            // 遍历当前行所有的View
            for (int j = 0; j < lineViews.size(); j++) {
                View child = lineViews.get(j);
                if (child.getVisibility() == View.GONE) {
                    continue;
                }
                MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

                //计算childView的left,top,right,bottom
                int lc = left + lp.leftMargin;
                int tc = top + lp.topMargin;
                int rc =lc + child.getMeasuredWidth();
                int bc = tc + child.getMeasuredHeight();

                child.layout(lc, tc, rc, bc);

                left += child.getMeasuredWidth() + lp.rightMargin + lp.leftMargin;
            }
            left = 0;
            top += lineHeight;
        }

    }

    /**
     * @param context 需要外部传入context，用于动态创建控件
     * @param strings 要展示的控件名称
     */
    public  void setData(Context context,ArrayList<String> strings){
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(10, 10, 10, 10);

        removeAllViews();

        for (int i = 0; i < strings.size(); i++) {
            TextView tv = new TextView(context);
            tv.setPadding(10, 10, 10, 10);
            if (i%2==0) {
                tv.setBackgroundColor(Color.RED);
            }else {
                tv.setBackgroundColor(Color.YELLOW);
            }
            tv.setText(strings.get(i));
            tv.setLayoutParams(layoutParams);
            addView(tv);
        }

    }

}
